package com.bawei.websocketdemo.test;

import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/28 09:58
 * @Description : SocketUtils
 */
public class YaoSocketUtils {
    private YaoSocketUtils(){}
    private static YaoSocketUtils yaoSocketUtils;
    public static YaoSocketUtils getInstance(){
        if(yaoSocketUtils == null){//第一次：避免每次判断锁是否被其他线程占用，节省资源
            synchronized (YaoSocketUtils.class){
                if(yaoSocketUtils == null){//第二次：避免创建多个实例

                    yaoSocketUtils = new YaoSocketUtils();
                }
            }
        }
        return yaoSocketUtils;
    }
    private YaoWebSocketClient yaoWebSocketClient;

    /**
     * 建立链接
     */
    public void initWS(){
        URI uri = URI.create("ws://124.70.98.255:8083/api/socket/100");
        yaoWebSocketClient = new YaoWebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                super.onClose(code, reason, remote);


            }

            @Override
            public void onMessage(String message) {
                super.onMessage(message);
            }

            @Override
            public void onError(Exception ex) {
                super.onError(ex);
            }
        };
        //设置超时重连
        yaoWebSocketClient.setConnectionLostTimeout(110*1000);
        //链接服务器
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    yaoWebSocketClient.connectBlocking();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /**
     * 发送数据
     * @param message
     */
    public void sendMessage(String message){
        if(yaoWebSocketClient != null && yaoWebSocketClient.isOpen()){
            yaoWebSocketClient.send(message);
        }
    }

    /**
     * 关闭链接
     */
    public void close(){
        if(yaoWebSocketClient != null && yaoWebSocketClient.isOpen()){
            yaoWebSocketClient.close();
        }
    }
}
